import "dart:convert";
import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/check_in/widget/cohabitant/index.dart";
import "package:ct_pa_majordomo/pages/apartment/check_in/widget/rent_info/index.dart";
import "package:ct_pa_majordomo/pages/apartment/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/common.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/form_validator.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/widgets/wrap_item.dart";
import "package:dio/dio.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:provider/provider.dart";

class CheckIn extends StatefulWidget {
  final Map room;
  const CheckIn({super.key, required this.room});

  @override
  State<StatefulWidget> createState() => _CheckInState();
}

class _CheckInState extends State<CheckIn> {
  late ImagePicker _imagePicker;
  XFile? _imageFile;
  int? _apartmentId;
  final Text _required =
      const Text("*", style: TextStyle(color: ThemeVars.colorError));
  final List _dateList = ["1月", "3月", "6月", "1年"];
  int _dateCheckIndex = -1;
  Map _params = {
    "checkInStart": DateTools.formatTime(DateTime.now().millisecondsSinceEpoch, format: "{y}-{m}-{d}"),
    "checkInEnd": DateTools.formatTime(DateTime.now().millisecondsSinceEpoch, format: "{y}-{m}-{d}"),
    "cohabitantList": [],
    "mainRenter": {
      "name": "",
      "contacts": "",
      "idCardNumber": "",
      "picUrl": "",
      "mainFlag": 1,
    },
    "rentObject": {},
    "remark": ""
  };

  bool _validate() {
    return _params["mainRenter"]?["name"].isNotEmpty && _params["mainRenter"]?["contacts"].isNotEmpty && _params["rentObject"].isNotEmpty;
  }

  String _formatDate(DateTime date) {
    return DateTools.formatTime(date.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
  }

  void _submit() async {
    Map<String, dynamic> data = {
      ..._params,
      "renterList": [_params["mainRenter"], ..._params["cohabitantList"]],
      "apartmentId": _apartmentId,
      "roomId": widget.room["roomId"],
    };
    data.remove("mainRenter");
    data.remove("cohabitantList");

    await apartmentApi.checkIn(data);
    EasyLoading.showSuccess("办理成功");
    if (context.mounted) {
      Navigator.pop(context, true);
    }
  }

  // 图片上传
  Future<void> _uploadImage() async {
    FormData formData = FormData();
    formData.files.add(MapEntry("file", await MultipartFile.fromFile(_imageFile!.path, filename: _imageFile!.name)));
    Map res = await commonApi.upload(formData);
    setState(() {
      _params["mainRenter"]["picUrl"] = res["data"]["url"];
    });
    print("图片信息：$res");
  }

  // 选择图片
  Future<void> _pickImage() async {
    final pickedImage = await _imagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _imageFile = pickedImage;
    });
  }

  Widget _renderFace() {
    Map mainRenter = _params["mainRenter"];
    if (_imageFile != null) {
      return Image.file(
        File(_imageFile!.path),
        width: 150,
        height: 150,
      );
    } else if (mainRenter["picUrl"] != null && mainRenter["picUrl"].isNotEmpty) {
      return Image.network(
        mainRenter["picUrl"],
        width: 150,
        height: 150,
      );
    }
    return Container(
      width: 150,
      height: 150,
      decoration: const BoxDecoration(
        color: ThemeVars.colorBackground,
      ),
      child: const Icon(Icons.add, size: 50,),
    );
  }

  @override
  void initState() {
    _imagePicker = ImagePicker();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // final Map? apartment = Provider.of<CommonState>(context).apartment;
    final Map? apartment = jsonDecode(storage.getString("apartment") ?? "");
    _apartmentId = apartment?["apartmentId"];
    return NormalScaffold(
      title: "办理入住",
      child: ListView(
        children: [
          Container(
            padding: const EdgeInsets.all(ThemeVars.paddingPage),
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            child: Text("公寓 A202"),
          ),
          const SizedBox(height: 12,),
          MenuBlock(
            title: Text("入住人信息"),
            items: [
              MenuBlockItem(
                text: "姓名",
                prefix: _required,
                showArrow: false,
                suffix: TextFormField(
                  decoration: InputDecoration(
                    hintText: "请输入",
                    border: InputBorder.none,
                    hintStyle: TextStyle(fontSize: 14),
                    isDense: true,
                  ),
                  initialValue: _params["mainRenter"]?["name"],
                  textAlign: TextAlign.right,
                  onChanged: (value) => setState(() {
                    _params["mainRenter"]?["name"] = value;
                  }),
                )
              ),
              MenuBlockItem(
                  text: "联系方式",
                  prefix: _required,
                  showArrow: false,
                  suffix: TextFormField(
                    decoration: InputDecoration(
                      hintText: "请输入手机号或者邮箱",
                      border: InputBorder.none,
                      hintStyle: TextStyle(fontSize: 14),
                      isDense: true,
                    ),
                    keyboardType: TextInputType.number,
                    initialValue: _params["mainRenter"]?["contacts"],
                    textAlign: TextAlign.right,
                    onChanged: (value) => setState(() {
                      _params["mainRenter"]?["contacts"] = value;
                    }),
                  )
              ),
              // 办理入住时先隐藏人脸认证 因为人脸需要renterId，入住办理时操作不了
              // MenuBlockItem(
              //   text: "人脸",
              //   showArrow: false,
              //   tip: Column(
              //     crossAxisAlignment: CrossAxisAlignment.start,
              //     children: [
              //       _renderFace(),
              //       const Text("人脸仅用于租客门禁开锁使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),)
              //     ],
              //   ),
              //   // suffix: Icon(Icons.image_outlined),
              //   onTap: () {
              //     _pickImage();
              //   },
              // ),
              MenuBlockItem(
                  text: "证件号",
                  showArrow: false,
                  tip: const Text("证件号仅用于租客办理入住登记使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),),
                  suffix: TextFormField(
                    decoration: InputDecoration(
                      hintText: "请输入",
                      border: InputBorder.none,
                      hintStyle: TextStyle(fontSize: 14),
                      isDense: true,
                    ),
                    initialValue: _params["mainRenter"]?["idCardNumber"],
                    textAlign: TextAlign.right,
                    onChanged: (value) => setState(() {
                      _params["mainRenter"]?["idCardNumber"] = value;
                    }),
                  )
              ),
              MenuBlockItem(
                text: "同住人",
                suffix: _params["cohabitantList"].length > 0
                    ? Text("${ _params["cohabitantList"].length}人", style: const TextStyle(fontSize: 14),)
                    : const Text("请选择", style: TextStyle(fontSize: 14, color: ThemeVars.colorTextSec),),
                onTap: () {
                  Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                    return Cohabitant(cohabitantList: _params["cohabitantList"]);
                  })).then((cohabitantList) {
                    if (cohabitantList != null) {
                      setState(() {
                        _params["cohabitantList"] = cohabitantList;
                      });
                    }
                  });
                }
              ),
              MenuBlockItem(
                text: "备注",
                suffix: Text(_params["remark"].isNotEmpty ? "已填写" : "请选择", style: TextStyle(fontSize: 14, color: ThemeVars.colorTextSec),),
                onTap: () {
                  Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                    return EditRemark(remark: _params["remark"]);
                  })).then((remark) {
                    if (remark != null) {
                      setState(() {
                        _params["remark"] = remark;
                      });
                    }
                  });
                }
              )
            ]
          ),
          const SizedBox(height: 12,),
          MenuBlock(
            title: Text("入住周期"),
            content: Wrap(
              spacing: 12,
              children: List.generate(_dateList.length, (index) {
                return WrapItem(
                    span: 3,
                    child: SizedBox(
                      height: 24,
                      child: Button(
                        type: _dateCheckIndex == index ? ButtonType.primaryLight : ButtonType.primaryOutline,
                        onPressed: () {
                          setState(() {
                            _dateCheckIndex = index;
                            int month = 0;
                            switch(index) {
                              case 0:
                                month = 1;
                                break;
                              case 1:
                                month = 3;
                                break;
                              case 2:
                                month = 6;
                                break;
                              case 3:
                                month = 12;
                                break;
                            }
                            DateTime date = DateTime.parse(_params["checkInStart"]);
                            DateTime futureDate =  DateTime(date.year, date.month + month, date.day - 1);
                            print("时间：》》》》${_formatDate(futureDate)}");
                            _params["checkInEnd"] = _formatDate(DateUtils.addDaysToDate(futureDate, -1));
                          });
                        },
                        child: Text(_dateList[index], textAlign: TextAlign.center, style: TextStyle(fontSize: 12),),
                      ),
                    )
                );
              })
            ),
            items: [
              MenuBlockItem(
                text: "开始时间",
                prefix: _required,
                suffix: Text(_params["checkInStart"].toString()),
                onTap: () {
                  showDatetimePicker(
                    context: context,
                    initialDateTime: DateTime.now(),
                    onchange: (value) => setState(() {
                      _params["checkInStart"] = DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
                    }),
                  );
                }
              ),
              MenuBlockItem(
                  text: "结束时间",
                  prefix: _required,
                  suffix: Text(_params["checkInEnd"].toString()),
                  onTap: () {
                    showDatetimePicker(
                      context: context,
                      initialDateTime: DateTime.now(),
                      onchange: (value) => setState(() {
                        _params["checkInEnd"] = DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
                      }),
                    );
                  }
              ),
              MenuBlockItem(
                  text: "房租信息",
                  prefix: _required,
                  suffix: Text(_params["rentObject"].isEmpty ?  "请填写" : "已填写", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 14),),
                  onTap: () {
                    // Stacker.pushNamed(
                    //   Keys.CHECK_IN_DETAIL_RENT_INFO,
                    //   arguments: {
                    //     "changeInfo": (value) {
                    //       setState(() {
                    //         _params["rentObject"] = value;
                    //       });
                    //     },
                    //   },
                    //
                    Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                      return RentInfo(
                        rentObject: _params["rentObject"],
                        changeInfo: (value) {
                          setState(() {
                            _params["rentObject"] = value;
                          });
                        });
                    }));
                  }
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(ThemeVars.paddingPage, 50, ThemeVars.paddingPage, 30),
            child: Button(
              onPressed: _validate() ? () async {
                if (!CommonTools.phone(_params["mainRenter"]?["contacts"])) {
                  EasyLoading.showToast("请输入正确的手机号码");
                  return;
                }
                if (_imageFile != null) {
                  await _uploadImage();
                }
                _submit();
              } : null,
              child: Text("确定")
            ),
          )
        ],
      ),
    );
  }

}